package cn.snow.boot.weather.service.impl;

import cn.snow.boot.weather.service.WeatherService;
import cn.snow.boot.weather.vo.WeatherResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * ${DESC}
 *
 * @author liuwanxiang
 * @version 2017/9/10
 */
@Service
public class WeatherServiceImpl implements WeatherService {

    @Autowired
    private RestTemplate restTemplate;

    private static final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini";


    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        return this.doGetWeatehrData(WEATHER_API + "?citykey=" + cityId);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        return this.doGetWeatehrData(WEATHER_API + "?city=" + cityName);
    }


    private WeatherResponse doGetWeatehrData(String uri) {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);

        String strBody = null;

        if (responseEntity.getStatusCodeValue() == 200) {
            strBody = responseEntity.getBody();
        }

        ObjectMapper mapper = new ObjectMapper();
        WeatherResponse weatherResponse = null;

        try {
            weatherResponse = mapper.readValue(strBody, WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return weatherResponse;

    }
}



